<template>
  <div class="app-container">
    <div class="filter-container">

      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>

      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <!-- {{ searchOptions }} -->

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      stripe
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" type="index" align="center" width="80" />
      <el-table-column show-overflow-tooltip label="文件名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.fileName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片显示" align="center">
        <template slot-scope="{row}">
          <el-image
            :src="row.fileUrl"
            :zoom-rate="1.2"
            :preview-src-list="[row.fileUrl]"
            :initial-index="0"
            fit="cover"
          />

        </template>
      </el-table-column>

      <el-table-column show-overflow-tooltip label="图片链接" align="center">
        <template slot-scope="{row}">
          <el-link type="primary" :href="row.fileUrl" target="_blank">{{ row.fileUrl }}</el-link>
        </template>
      </el-table-column>

      <el-table-column show-overflow-tooltip label="跳转地址" align="center">
        <template slot-scope="{row}">
          <el-link type="success" :href="row.fileUrlTo" target="_blank">{{ row.fileUrlTo }}</el-link>
        </template>
      </el-table-column>

      <el-table-column label="文件类型" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.fileTag=='jpg'||row.fileTag=='jpeg'" color="#79bbff" style="color: rgb(255, 255, 255);border: none;">
            {{ row.fileTag }}
          </el-tag>
          <el-tag v-else-if="row.fileTag=='png'" color="#eebe77" style="color: rgb(255, 255, 255);border: none;">
            {{ row.fileTag }}
          </el-tag>
          <el-tag v-else-if="row.fileTag==''" style="color: rgb(255, 255, 255);border: none;" />
        </template>
      </el-table-column>

      <el-table-column show-overflow-tooltip label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />
    <!-- {{ total }} {{ listQuery }} -->

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
        {{ temp }}
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="temp.fileName" disabled placeholder="文件名" style="width: 300px;" />
        </el-form-item>

        <el-form-item label="图片上传" prop="fileUrl">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :action="uploadUrl"
            :data="{id:temp.id,fileName:temp.fileName,fileClassify:0,fileUrlTo:temp.fileUrlTo}"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-change="handleUploadChange"
            :auto-upload="false"
          >
            <div class="image-container">
              <el-image
                v-if="temp.fileUrl"
                :src="temp.fileUrl"
                :zoom-rate="1.0"
                fit="cover"
                style="width: 100%;height: 100%;object-fit: cover;display: block;"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon" style="padding: 20px;" />

              <div v-if="temp.fileUrl" class="image-overlay">
                <i class="el-icon-edit" />
              </div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="跳转链接" prop="fileUrlTo">
          <el-input v-model="temp.fileUrlTo" placeholder="请填写跳转链接" style="width: 300px;" />
        </el-form-item>

        <!-- {{ temp }} -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchBanner, deleteBanner } from '@/api/setting'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox } from 'element-ui'

function compare(attr, rev) {
  if (rev === undefined) {
    rev = 1
  } else {
    rev = (rev) ? 1 : -1
  }

  return function(a, b) {
    a = a[attr]
    b = b[attr]
    if (a < b) {
      return rev * -1
    }
    if (a > b) {
      return rev * 1
    }
    return 0
  }
//   return function(a, b) {
//     var value1 = a[property]
//     var value2 = b[property]
//     return value1 - value2
//   }
}

export default {
  name: 'Wxusermanager',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      uploadUrl: 'https://braincognitiontec.top:30005/static-file/upload-img',
      infoTitle: '详情',
      ori_data: null,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      searchOptions: {
        yearmonth: '',
        failureType: '',
        orderProcess: ''
      },
      showReviewer: false,
      temp: {
        id: '',
        fileName: '',
        filePath: '',
        fileUrl: '',
        fileUrlTo: '',
        fileClassify: '',
        fileTag: '',
        createTime: '',
        updateTime: '',
        deleted: ''
      },
      dialogFormVisible: false,
      dialogINFOFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        info: '详情'
      },
      rules: {
        fileName: [{ required: true, message: '必填', trigger: 'change' }],
        fileUrlTo: [{ required: true, message: '必填', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchBanner({ 'fileClassify': 0 }).then(response => {
        const BannerInfo = response.data.data
        this.ori_data = BannerInfo

        this.list = this.ori_data
        this.list.sort(compare('fileName'))

        this.list = this.list.map(element => {
          element.fileName = element.fileName.split('.')[0]
          return element
        })

        this.total = BannerInfo.length

        setTimeout(() => {
          this.listLoading = false
        }, 0.6 * 1000)
      })
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        id: '',
        fileName: '',
        filePath: '',
        fileUrl: '',
        fileUrlTo: '',
        fileClassify: '',
        fileTag: '',
        createTime: '',
        updateTime: '',
        deleted: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.temp.fileName = 'Banner' + (this.total + 1)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      if (this.temp.fileUrl === '') {
        this.$message.error('必须上传图片')
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$refs.upload.submit()
        }
      })
    },
    handleInfo(row, index) {
      this.dialogINFOFormVisible = true
    },
    handleUpdate(row) {
      this.resetTemp()
      this.temp = row
      // this.uploadUrl = 'https://braincognitiontec.top:30005/static-file/update/byId'

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      if (this.temp.fileUrl === '') {
        this.$message.error('必须上传图片')
      }
      this.$refs['dataForm'].validate((valid) => {
        fetch(this.temp.fileUrl)
          .then(res => res.blob())
          .then(blob => {
            const newfile = new File([blob], `${this.temp.fileName}.${this.temp.fileTag}`, { type: this.temp.fileTag === 'png' ? 'image/png' : 'image/jpeg' })

            this.$refs.upload.handleStart(newfile)

            deleteBanner({ 'id': this.temp.id }).then(res => {
              this.$refs.upload.submit()
            })
          })
      })
    },
    handleDelete(row, index) {
      MessageBox.confirm('您将要删除该资源且无法复原,是否确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBanner({ 'id': row.id }).then(res => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['文件名', '图片链接', '跳转链接', '文件类型', '创建时间']
        const filterVal = ['fileName', 'fileUrl', 'fileUrlTo', 'fileTag', 'createTime']
        const data = this.formatJson(filterVal)
        // console.log(data)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-banners'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j.split('.')[0] === 'detail') {
            // console.log(v['detail'][j.split('.')[1]])
            return v['detail'][j.split('.')[1]]
          } else {
            // console.log(v[j])
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    handleUploadChange(file) {
      file = file.raw
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
        return false
      }
      const isLt1M = file.size / 1024 / 1024 < 2
      if (!isLt1M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }

      const url = URL.createObjectURL(file)
      this.temp.fileUrl = url
    },
    beforeUpload(file) {
      return true
    },
    handleUploadSuccess(response) {
      if (response.success === false) {
        this.$message.error(response.errorMsg || '上传失败!请重新上传')
      } else {
        this.$message.success('上传成功!')
        this.dialogFormVisible = false
      }
    },
    handleUploadError(res) {
      this.$message.error('上传失败!请重新上传')
    }

  }}

</script>

<style lang="scss">
.image-container {
  position: relative;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.image-overlay i {
  font-size: 24px;
  color: #fff;
}
</style>
